package com.cauli.file.component;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cauli.file.model.dto.file.FileSearchDTO;
import com.cauli.file.model.entity.Share;
import com.cauli.file.service.ShareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Cauli
 * @date 2023/9/2 23:50
 * @description 过期的分享文件监听器
 */
@Slf4j
@Component
@RabbitListener(queues = "my-dlx-queue")
public class ExpiredShareFileListener {
    @Autowired
    private ShareService shareService;

    // 死信相关
    public static final String DEAD_LETTER_EXCHANGE = "deadLetter.exchange";
    public static final String DEAD_LETTER_QUEUE = "deadLetter.queue";
    public static final String KEY_FILE_DEAD_LETTER = "key.file.dead.letter";

    @RabbitListener(bindings = {
            @QueueBinding(
                    key = KEY_FILE_DEAD_LETTER,
                    value = @Queue(value = DEAD_LETTER_QUEUE, durable = "true"),
                    exchange = @Exchange(value = DEAD_LETTER_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true")
            )})
    public void receiveShareMessage(Share share) {
        log.info("监听到文件过期处理操作：{}", share);

        // 将share的分享状态改为已过期 → 将share的shareStatus由0改为1
        LambdaUpdateWrapper<Share> shareLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        shareLambdaUpdateWrapper.set(Share::getShareStatus, 1)
                .eq(Share::getShareBatchNum, share.getShareBatchNum());
        shareService.update(share, shareLambdaUpdateWrapper);

        log.info("操作完成：{}", share);
    }
}
